package com.yksj.healthtalk.ui.setting;

import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import org.cropimage.CropUtils;
import org.handmark.pulltorefresh.library.PullToRefreshBase;
import org.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import org.handmark.pulltorefresh.library.PullToRefreshScrollView;
import org.json.JSONException;
import org.json.JSONObject;
import org.universalimageloader.core.ImageLoader;
import org.universalimageloader.utils.StorageUtils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Parcelable;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.yksj.healthtalk.adapter.InterestAdapter;
import com.yksj.healthtalk.comm.BaseFragmentActivity;
import com.yksj.healthtalk.comm.SearchByTagActivity;
import com.yksj.healthtalk.comm.ZoomImgeDialogFragment;
import com.yksj.healthtalk.db.DictionaryHelper;
import com.yksj.healthtalk.entity.CustomerInfoEntity;
import com.yksj.healthtalk.entity.TagEntity;
import com.yksj.healthtalk.net.http.HttpRestClient;
import com.yksj.healthtalk.net.http.JsonsfHttpResponseHandler;
import com.yksj.healthtalk.net.http.ObjectHttpResponseHandler;
import com.yksj.healthtalk.net.http.RequestParams;
import com.yksj.healthtalk.net.socket.SmartFoxClient;
import com.yksj.healthtalk.ui.R;
import com.yksj.healthtalk.ui.app.HTalkApplication;
import com.yksj.healthtalk.ui.home.ChooseTagsActivity;
import com.yksj.healthtalk.ui.login.DoctorRegisteUI;
import com.yksj.healthtalk.ui.views.TagsGridView;
import com.yksj.healthtalk.utils.BitmapUtils;
import com.yksj.healthtalk.utils.DataParseUtil;
import com.yksj.healthtalk.utils.ImageUtils;
import com.yksj.healthtalk.utils.SystemUtils;
import com.yksj.healthtalk.utils.ToastUtil;
import com.yksj.healthtalk.utils.WheelUtils;

public class PersonalInformationActivity extends BaseFragmentActivity implements
		OnClickListener, OnRefreshListener<ScrollView>, OnItemClickListener {

	private DictionaryHelper dictionaryHelper;
	private View mainView;
	private View wheelView;
	private PopupWindow pop;
	private PopupWindow listpop;
	private PopupWindow agepop;// 年龄的pop
	private ImageView my_photo;
	private int textNumber = 0;
	private EditText necheng;
	private TextView customer_id;
	private EditText customer_explan;
	private TextView xingbie;
	private TextView hunyin;
	private TextView zhiye;
	private TextView xueli;
	private TextView shengri;
	private TextView CURRENTVIEW;
	private TextView suozaidi;
	private TextView textNum;
	private String mNameInput;
	private String mCustomerInput;
	private TextView doctorTv;
	private File currentCameraFile;
	private TextView duomeiCoin;
	private String headImagePath;
	public final int PHOTOHRAPH = 1001;// 拍照
	public final int PHOTORESOULT = 1003;// 结果
	private final int ONEREQUEST = 1000;// 第一次请求数据
	public int Flag = 0;
	private TagsGridView mGridXingQu, mGridBody;// 兴趣grid
	public final int GET_PERSONAL_HEAD_IMAGE = 1004; // 获取头像
	private final int WHAT_PERSON_XINGQU = 100;// 兴趣list选择
	private final int WHAT_PERSON_BODY = 101;// 身体选择
	protected final int UPDATE_HEADER = 102;
	private CustomerInfoEntity mCus;// 实体
	private ImageLoader mImageLoader;
	private InterestAdapter mAdapterBody, mAdapterXingQu;
	private List<TagEntity> mBodyList, mXingQuList;
	protected boolean onbackKey = true;//
	private boolean isEdit = false;// 是否为编辑状态
	boolean onItem = false;// 标签是否修改
	private List<Map<String, String>> proList = null;
	private Map<String, List<Map<String, String>>> cityMap = new LinkedHashMap<String, List<Map<String, String>>>();
//	private String mPhotoURL;// 照相的路径
	private String locationCode = "";
	private RelativeLayout person_doctor_line;
	private RelativeLayout personQrcode_line;
	private PullToRefreshScrollView mPullRefreshScrollView;
	private File headerFile;//拍照文件

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.personal_information_set);

		mPullRefreshScrollView = (PullToRefreshScrollView) findViewById(R.id.pull_refresh_scrollview);
		mPullRefreshScrollView.setOnRefreshListener(this);
		mImageLoader = ImageLoader.getInstance();
		dictionaryHelper = DictionaryHelper.getInstance(this);
		mCus = SmartFoxClient.getSmartFoxClient().getCustomerInfoEntity();
		initText();
		queryData();
	}

	/**
	 * 控制scrollview在顶部定位
	 */
	private void scrollTop() {
		mPullRefreshScrollView.getRefreshableView().scrollTo(0, 0);
		mPullRefreshScrollView.getRefreshableView().smoothScrollTo(0, 0);
	}

	@Override
	protected void onRestart() {
		Flag = ONEREQUEST;
		super.onRestart();
	}

	/**
	 * 初始化控件
	 */
	@SuppressLint("ResourceAsColor")
	public void initText() {
		initTitle();
		LayoutInflater inflater = LayoutInflater.from(this);
		mainView = inflater.inflate(R.layout.personal_information_set, null);
		wheelView = inflater.inflate(R.layout.wheel, null);
		wheelView.findViewById(R.id.wheel_cancel).setOnClickListener(this);
		wheelView.findViewById(R.id.wheel_sure).setOnClickListener(this);
		pop = new PopupWindow(wheelView, LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT);
		View checklist = inflater.inflate(R.layout.personal_photo_check, null);
		listpop = new PopupWindow(checklist, LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT);

		checklist.findViewById(R.id.bendifenjian).setOnClickListener(PersonalInformationActivity.this);
		checklist.findViewById(R.id.paizhao).setOnClickListener(PersonalInformationActivity.this);
		checklist.findViewById(R.id.quxiao).setOnClickListener(PersonalInformationActivity.this);

		titleLeftBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				SystemUtils.hideSoftBord(getApplicationContext(), necheng);
				if (!isEdit() && isEdit) {
					onSaveYesOn();
				} else {
					onBackPressed();
				}
			}
		});
		my_photo = (ImageView) findViewById(R.id.customer_data_image);
		my_photo.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				SystemUtils.hideSoftBord(getApplicationContext(), necheng);
				if (mCus.isAudit() || mCus.isShow()) {//如果是医生,不能编辑头像
					if (mCus.bigHeadIcon == null || "".equals(mCus.bigHeadIcon)
							|| (isEdit)) {
						return;
					}
					if(TextUtils.isEmpty(mCus.bigHeadIcon))return; ZoomImgeDialogFragment.show(mCus.bigHeadIcon,getSupportFragmentManager());
				} else {
					if ((!isEdit)) {
						if(TextUtils.isEmpty(mCus.bigHeadIcon))return; ZoomImgeDialogFragment.show(mCus.bigHeadIcon,getSupportFragmentManager());
					} else
						WheelUtils.setPopeWindow(PersonalInformationActivity.this, mainView,
								listpop);
				}
			}
		});
		TextView mTitle = (TextView) findViewById(R.id.title_lable);
		mTitle.setText("个人信息");
		necheng = (EditText) findViewById(R.id.customer_data_name);
		customer_id = (TextView) findViewById(R.id.customer_data_id);
		customer_explan = (EditText) findViewById(R.id.customer_data_add);

		duomeiCoin = (TextView) findViewById(R.id.duomei_coin);
		findViewById(R.id.add_view).setOnClickListener(this);
		findViewById(R.id.add_view2).setOnClickListener(this);
		findViewById(R.id.add_view3).setOnClickListener(this);
		findViewById(R.id.add_view5).setOnClickListener(this);
		findViewById(R.id.add_view6).setOnClickListener(this);
		findViewById(R.id.add_view7).setOnClickListener(this);
		suozaidi = (TextView) findViewById(R.id.name_info);
		shengri = (TextView) findViewById(R.id.name_info3);
		xueli = (TextView) findViewById(R.id.xueli_info);
		zhiye = (TextView) findViewById(R.id.zhiye_info);
		hunyin = (TextView) findViewById(R.id.hunyin_info);
		xingbie = (TextView) findViewById(R.id.xingbie_info);
		textNum = (TextView) findViewById(R.id.textcount);
		customer_explan.addTextChangedListener(textWatcher);
		doctorTv = (TextView) findViewById(R.id.person_doctor);
		doctorTv.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent i = new Intent(PersonalInformationActivity.this,DoctorRegisteUI.class);
				startActivity(i);
			}
		});

		person_doctor_line = (RelativeLayout) findViewById(R.id.person_doctor_line);
		person_doctor_line.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent i = new Intent(PersonalInformationActivity.this,	DoctorRegisteUI.class);
				startActivity(i);
			}
		});

		personQrcode_line = (RelativeLayout) findViewById(R.id.person_qrcode_line);
		personQrcode_line.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(PersonalInformationActivity.this,SettingQrCodeActivity.class);
				intent.putExtra("id", SmartFoxClient.getLoginUserId());
				intent.putExtra("type", 0);
				startActivity(intent);
			}
		});

		if (mCus != null && mCus.isDoctor()) {
			doctorTv.setText(R.string.lookDoctotInfo);
			findViewById(R.id.doctor_line).setVisibility(View.GONE);
		} else {
			doctorTv.setText(R.string.openDoctor);
		}

		if ("".equals(mCus.getName())) {
			necheng.setHint(getString(R.string.nickname));
		} else {
			necheng.setText(mCus.getName());
		}
		customer_id.setText(mCus.getUsername());
		if (mCus.getDescription() != null&& mCus.getDescription().length() == 0) {
			textNum.setText("0/70");
		} else {
			customer_explan.setText(mCus.getDescription().toString());
			textNum.setText(mCus.getDescription().trim().length() + "/70");
		}
		if (!"".equals(mCus.getDwellingplace()))
			suozaidi.setText(mCus.getDwellingplace());

		if (mCus.getBirthday() != null) {
			if (mCus.getBirthday().length() == 8) {
				shengri.setText(mCus.getBirthday().substring(0, 4)
						+ getResources().getString(R.string.nian)
						+ mCus.getBirthday().substring(4, 6)
						+ getResources().getString(R.string.yue)
						+ mCus.getBirthday().substring(6, 8)
						+ getResources().getString(R.string.ri));
			} else {
				shengri.setText(mCus.getBirthday());
			}
		}
		if (mCus.getCultureLevel() == null
				|| mCus.getCultureLevel().toString().length() == 0) {
		} else {
			xueli.setText(mCus.getCultureLevel());
		}
		if (mCus.getMetier() == null || mCus.getMetier().trim().length() == 0) {
		} else {
			zhiye.setText(mCus.getMetier());
		}
		if (mCus.getHunyin() == null || mCus.getHunyin().trim().length() == 0) {
		} else {
			hunyin.setText(mCus.getHunyin());
		}

		if (mCus.getSex() == null && mCus.getSex().trim().length() == 0) {
			xingbie.setText("保密");
		} else {

			String sexflag = mCus.getSex();
			if (sexflag.equals("2")) {
				xingbie.setText("女");
			} else if (sexflag.equals("1")) {
				xingbie.setText("男");
			} else {
				xingbie.setText("保密");
			}
		}
		setPerspnImage();
		duomeiCoin.setText(mCus.getMoney() + "");
		mGridXingQu = (TagsGridView) findViewById(R.id.xingqu_grid);
		mXingQuList = DataParseUtil.JsonToListEntity(mCus.getAttention(), 0);
		mAdapterXingQu = new InterestAdapter(this, mXingQuList,
				R.layout.textiterm);
		mGridXingQu.setAdapter(mAdapterXingQu);

		mGridBody = (TagsGridView) findViewById(R.id.body_grid);
		mBodyList = DataParseUtil.JsonToListEntity(mCus.getSameExperience(), 1);
		mAdapterBody = new InterestAdapter(this, mBodyList, R.layout.textiterm);
		mGridBody.setAdapter(mAdapterBody);
		mGridXingQu.setOnItemClickListener(this);
		mGridBody.setOnItemClickListener(this);

		customer_explan.setEnabled(false);
		necheng.setEnabled(false);

		titleRightBtn2.setText("编辑");
		titleRightBtn2.setVisibility(View.VISIBLE);
		titleRightBtn2.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				isEdit = !isEdit;
				if (!isEdit) {
					SystemUtils.hideSoftBord(getApplicationContext(), necheng);
					customer_explan.setEnabled(false);
					necheng.setEnabled(false);
					textNum.setVisibility(View.GONE);
					necheng.setTextColor(Color.BLACK);
					findViewById(R.id.my_doctor).setVisibility(View.VISIBLE);
					findViewById(R.id.my_qrcode).setVisibility(View.VISIBLE);
					person_doctor_line.setVisibility(View.VISIBLE);
					personQrcode_line.setVisibility(View.VISIBLE);
					changeAdapter(false);
					necheng.setBackgroundDrawable(null);
					if (!isEdit())
						changePersonSubmit();
					titleRightBtn2.setText("编辑");
					customer_explan.setHint("");
					
				} else {
					titleRightBtn2.setText("完成");
					customer_explan.setEnabled(true);
					textNum.setVisibility(View.VISIBLE);
					necheng.setEnabled(true);
					if (!mCus.isDoctor()) {
						necheng.setTextColor(Color.WHITE);
						necheng.setBackgroundResource(R.drawable.dise);
					}
					person_doctor_line.setVisibility(View.GONE);
					personQrcode_line.setVisibility(View.GONE);
					findViewById(R.id.my_doctor).setVisibility(View.GONE);
					findViewById(R.id.my_qrcode).setVisibility(View.GONE);
					changeAdapter(true);
					customer_explan.setHint("请输入描述");
				}
			}
		});
	}

	private void changeAdapter(boolean fla) {
		TagEntity tagEntity = new TagEntity("000", "+");
		if (fla) {
			if (!mBodyList.contains(tagEntity)) {
				mBodyList.add(mBodyList.size(), new TagEntity("000", "+"));
			}
			if (!mXingQuList.contains(tagEntity)) {
				mXingQuList.add(mXingQuList.size(), new TagEntity("000", "+"));
			}

		} else {
			if (mBodyList.contains(tagEntity))
				mBodyList.remove(new TagEntity("000", "+"));
			if (mXingQuList.contains(tagEntity))
				mXingQuList.remove(new TagEntity("000", "+"));
		}
		mAdapterXingQu.notifyDataSetChanged();
		mAdapterBody.notifyDataSetChanged();

	}

	@Override
	protected void onResume() {
		super.onResume();
		scrollTop();
		mCus = SmartFoxClient.getSmartFoxClient().getCustomerInfoEntity();
		if (mCus != null && mCus.isDoctor()) {
			doctorTv.setText(R.string.lookDoctotInfo);
			findViewById(R.id.doctor_line).setVisibility(View.GONE);
		}
	}

	/*
	 * 判断是否编辑过
	 */
	private boolean isEdit() {
		String sexflag = mCus.getSex();
		mCustomerInput = customer_explan.getText().toString();
		mNameInput = necheng.getText().toString();
		if (sexflag.equals("2")) {
			sexflag = "女";
		} else if (sexflag.equals("1")) {
			sexflag = "男";
		} else {
			sexflag = "保密";
		}
		String birth = shengri.getText().toString();

		if (!mCus.getName().trim().equals(mNameInput.trim())) {
			return false;
		} else if (!mCus.getDescription().toString().equals(mCustomerInput)) {
			return false;
		} else if (!mCus.getDwellingplace().equals(
				suozaidi.getText().toString())) {
			return false;
		} else if (!mCus.getCultureLevel().equals(xueli.getText().toString())) {
			return false;
		} else if (!mCus.getMetier().equals(zhiye.getText().toString())) {
			return false;
		} else if (!mCus.getHunyin().equals(hunyin.getText().toString())) {
			return false;
		} else if (!sexflag.equals(xingbie.getText().toString())) {
			return false;
		} else if (!mCus.getBirthday().equals(birth)) {
			return false;
		} else if (headerFile != null) {
			return false;
		} else if (onItem) {
			return false;
		} else {
			return true;
		}

	}

	/**
	 * 点击编辑的时候,开启分线程查询并封转城市数据及信息层面数据
	 */
	private void queryData() {
		new Thread(new Runnable() {
			@Override
			public void run() {
				proList = dictionaryHelper.setCityData(
						PersonalInformationActivity.this, cityMap);
			}
		}).start();
	}

	@Override
	public void onClick(View v) {
		if (!isEdit)
			return;
		Intent intent;
		switch (v.getId()) {
		case R.id.wheel_cancel:
			if (pop != null)
				pop.dismiss();
			break;

		case R.id.wheel_sure:
			if (pop != null)
				pop.dismiss();
			if (WheelUtils.getCurrent() != null) {
				setText();
			}
			break;

		case R.id.wheel_cancel_age:
			break;

		case R.id.wheel_sure_age:
			if (CURRENTVIEW == shengri) {
				String[] str = (String[]) v.getTag();
				shengri.setText(str[0] + str[1] + str[2]);
			}
			break;
		case R.id.customer_data_image:
			break;

		case R.id.add_view3:// 城市
			CURRENTVIEW = suozaidi;
			setCity();
			break;

		case R.id.add_view2:// 年龄
			CURRENTVIEW = shengri;
			setAge();
			break;

		case R.id.add_view:// 性别
			CURRENTVIEW = xingbie;
			SystemUtils.hideSoftBord(this, necheng);
			setXingbie();
			break;

		case R.id.add_view5:// 学历
			CURRENTVIEW = xueli;
			setXueli();
			break;

		case R.id.add_view6:// 职业
			CURRENTVIEW = zhiye;
			setZhiye();
			break;

		case R.id.add_view7:// 婚姻
			CURRENTVIEW = hunyin;
			setHunyin();
			break;
		case R.id.paizhao: // 自拍照片
			listpop.dismiss();
			if (mCus.isDoctor())
				return;
			if (!SystemUtils.getScdExit()) {
				ToastUtil.showShort(this, R.string.chatting_sd_uninstall);
				return;
			}
//			currentCameraFile = StorageUtils.createCameraFile();
//			Uri uri = Uri.fromFile(currentCameraFile);
//			intent = CropUtils.createPickForCameraIntent(uri);
//			startActivityForResult(intent, PHOTOHRAPH);
			try {
				currentCameraFile = StorageUtils.createImageFile();
				Uri outUri = Uri.fromFile(currentCameraFile);
				intent = CropUtils.createPickForCameraIntent(outUri);
				startActivityForResult(intent,PHOTOHRAPH);
			} catch (Exception e) {
				e.printStackTrace();
				ToastUtil.showCreateFail();
			}
			break;

		case R.id.bendifenjian: // 相册选择图片
			listpop.dismiss();
			if (!SystemUtils.getScdExit()) {
				ToastUtil.showShort(PersonalInformationActivity.this,
						"SD卡拔出,壹健康用户头像,语音,图片等功能不可用");
				return;
			}
			intent = CropUtils.createPickForFileIntent();
			startActivityForResult(intent,PHOTORESOULT);
//			intent = getPhotoPickIntent();
//			startActivityForResult(intent, PHOTORESOULT);
			break;

		case R.id.quxiao:
			listpop.dismiss();
			break;
		}
	}

	/**
	 * 设置学历
	 */
	private void setXueli() {
		String[] xueli = getResources().getStringArray(R.array.xueli);
		WheelUtils.setSingleWheel(this, xueli, mainView, pop, wheelView, false);
	}

	/**
	 * 设置职业
	 */
	private void setZhiye() {
		String[] zhiye = getResources().getStringArray(R.array.zhiye);
		WheelUtils.setSingleWheel(this, zhiye, mainView, pop, wheelView, false);
	}

	/**
	 * 设置婚姻
	 */
	private void setHunyin() {
		String[] hunyin = getResources().getStringArray(R.array.hunyin);
		WheelUtils
				.setSingleWheel(this, hunyin, mainView, pop, wheelView, false);
	}

	/**
	 * 设置性别
	 */
	private void setXingbie() {
		String[] xingbie = getResources().getStringArray(R.array.sex);
		WheelUtils.setSingleWheel(this, xingbie, mainView, pop, wheelView,
				false);
	}

	/**
	 * 设置滚轮 城市数据
	 */
	private void setCity() {
		if (proList == null || cityMap == null) {
		} else {
			WheelUtils.setDoubleWheel(this, proList, cityMap, mainView, pop,
					wheelView);
		}
	}

	/**
	 * 设置年龄
	 */
	private void setAge() {
		if(agepop==null){
			agepop=WheelUtils.showThreeDateWheel(this, mainView, this);	
		}else{
			agepop.showAtLocation(mainView,Gravity.BOTTOM, 0, 0);
		}
		
	}

	/**
	 * 对滚轮选中的类容进行文本匹配
	 */
	public void setText() {
		if (CURRENTVIEW.equals(suozaidi)) {
			suozaidi.setText(WheelUtils.getCurrent());
		} else if (CURRENTVIEW.equals(shengri)) {
			shengri.setText(WheelUtils.getCurrent());
		} else if (CURRENTVIEW.equals(xueli)) {
			xueli.setText(WheelUtils.getCurrent());
		} else if (CURRENTVIEW.equals(zhiye)) {
			zhiye.setText(WheelUtils.getCurrent());
		} else if (CURRENTVIEW.equals(hunyin)) {
			hunyin.setText(WheelUtils.getCurrent());
		} else if (CURRENTVIEW.equals(xingbie)) {
			xingbie.setText(WheelUtils.getCurrent());
		}
		locationCode = WheelUtils.getCode();
	}

	/**
	 * 离开此页面判断是否保存已修改的
	 */
	private void onSaveYesOn() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(R.string.tishi);
		builder.setMessage(R.string.save_yes_no);
		builder.setPositiveButton(R.string.yes,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						onbackKey = false;
						changeAdapter(false);
						changePersonSubmit();
					}
				});
		builder.setNegativeButton(R.string.no,
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						finish();
						overridePendingTransition(R.anim.back_enter,
								R.anim.back_exit);
					}
				});
		builder.show();
	}

	public void changePersonSubmit() {
		mCustomerInput = customer_explan.getText().toString();
		String all = "^[a-zA-Z0-9\u4e00-\u9fa5\n[s| ]*r]{1,20}$";// 数字、字母，不能大于20位
		Pattern pattern1 = Pattern.compile(all);//
		if (!pattern1.matcher(mNameInput.trim()).matches()
				|| mNameInput.trim().equals("")) {
			toastOnUiThreadDialog(getString(R.string.nechengchairoutside));
			return;
		}
		if (mCustomerInput.length() > 100) {
			toastOnUiThreadDialog(getString(R.string.explanchairoutside));
			return;
		}
		JSONObject json = null;
		RequestParams requestParams = null;
		try {
			json = new JSONObject();
			json.put("customerNickname", mNameInput = mNameInput.trim()
					.replaceAll("\n", ""));// 呢称
			json.put("personalNarrate", mCustomerInput);// 一句话说明
			json.put("dwellingplace", suozaidi.getText().toString());// 所在地
			json.put("customerlocus", locationCode);// 所在地编码
			json.put("cultureLevel", xueli.getText().toString());// 学历
			json.put("metier", zhiye.getText().toString());// 职业
			json.put("marryFlag", hunyin.getText().toString());// 婚姻
			String xingbie_sex = xingbie.getText().toString();

			if ("男".equals(xingbie_sex)) {
				json.put("customerSex", "1");
			} else if ("女".equals(xingbie_sex)) {
				json.put("customerSex", "2");
			} else {
				json.put("customerSex", "0");
			}
			json.put("customerId", mCus.getId());
			json.put("clientIconBackground", mCus.getNormalHeadIcon());
			json.put("bigIconBackground", mCus.getBigHeadIcon());
			String birth = shengri.getText().toString();
			if (birth != null && birth.length() == 11) {
				json.put("birthday", birth);
			}
			json.put("bodyList", DataParseUtil.TagsListEntityToJson(mBodyList));
			json.put("interestsList",
					DataParseUtil.TagsListEntityToJson(mXingQuList));

			requestParams = new RequestParams();
			requestParams.put("json", json.toString());
			if (headerFile != null) {
				requestParams.put("file", headerFile);
			} else {
				requestParams.putNullFile("file", new File(""));
			}

		} catch (Exception e) {
			ToastUtil.showBasicShortToast(getApplicationContext(), "内部解析出错");
			return;
		}

		HttpRestClient.doHttpUpdatePerson(requestParams,new JsonsfHttpResponseHandler(this) {
					@Override
					public void onSuccess(int statusCode,com.alibaba.fastjson.JSONObject response) {
						if(response.containsKey("error_code")){
							ToastUtil.showShort("修改失败,请稍后重试...");
						}else{
							resetCustomInfo(response.toString());
							ToastUtil.showShort("修改成功..");
							finish();
						}
						super.onSuccess(statusCode, response);
					}
				});
	}

	/**
	 * 主线程toast
	 * 
	 * @param str
	 */
	private void toastOnUiThreadDialog(final String str) {
		PersonalInformationActivity.this.runOnUiThread(new Runnable() {
			@Override
			public void run() {
				ToastUtil.showShort(str);
			}
		});
	}

	/**
	 * 修改个人资料成功,重新同步个人资料
	 * 
	 * @throws JSONException
	 */
	private void resetCustomInfo(String str) {
		JSONObject object;
		try {
			object = new JSONObject(str);
			SmartFoxClient foxClient = SmartFoxClient.getSmartFoxClient();
			mCus = DataParseUtil.JsonTocuStomUpdate(object,foxClient.getCustomerInfoEntity());
			if (mCus != null) {
				foxClient.setCustomerInfoEntity(mCus);
				foxClient.setUserName(mCus.getUsername());
				HTalkApplication.getAppData().updateCacheInfomation(mCus);
			}
			if (headerFile != null)// 表示没有修改头像
				ImageUtils.deleBitmap(headerFile.getAbsolutePath());
		} catch (JSONException e) {
			ToastUtil.showShort("内部解析错误 ,请刷新资料");
		}
	}

	private TextWatcher textWatcher = new TextWatcher() {
		@Override
		public void afterTextChanged(Editable s) {
		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {
		}

		@Override
		public void onTextChanged(CharSequence s, int start, int before,
				int count) {
			if ((start + count) <= 70
					&& customer_explan.getText().toString().length() <= 100) {
				textNumber = customer_explan.getText().toString().length();
				textNum.setText(textNumber + "/70");
			} else {
				customer_explan.setText(s.subSequence(0,70));
				customer_explan.setSelection(s.subSequence(0, 70).length());
			}
		}
	};

	/**
	 * 显示图像
	 */
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case PHOTOHRAPH: // 拍照
			if(resultCode == Activity.RESULT_OK){
				String strFilePath = currentCameraFile.getAbsolutePath();
				onHandlerCropImage(strFilePath);
			}
//			if (resultCode != RESULT_OK)
//				return;
//			Bitmap bm = BitmapUtils.decodeBitmap(currentCameraFile.getAbsolutePath(), 900, 900);
//			if (bm == null)
//				return;
//			try {
//				mPhotoURLfile = StorageUtils.createHeaderFile();
//			} catch (Exception e) {
//				e.printStackTrace();
//			}
//			StorageUtils.saveImageOnImagsDir(bm, mPhotoURLfile);
//			mPhotoURL = mPhotoURLfile.getAbsolutePath();
//			my_photo.setImageBitmap(bm);
			break;
		case PHOTORESOULT: // 相册
			if(resultCode == Activity.RESULT_OK){
				if (data != null) {
					Uri uri = data.getData();
					String scheme = uri.getScheme();
					String strFilePath = null;//图片地址
					// url类型content or file
					if ("content".equals(scheme)) {
						strFilePath = getImageUrlByAlbum(uri);
					} else {
						strFilePath = uri.getPath();
					}
					onHandlerCropImage(strFilePath);
				}
			}
//			if (resultCode != RESULT_OK)
//				return;
//			if (data != null) {
//				Bitmap photo = data.getParcelableExtra("data");
//				if (photo == null)
//					return;
//				try {
//					mPhotoURLfile = StorageUtils.createHeaderFile();
//				} catch (Exception e) {
//					e.printStackTrace();
//				}
//				StorageUtils.saveImageOnImagsDir(photo, mPhotoURLfile);
//				mPhotoURL = mPhotoURLfile.getAbsolutePath();
//				my_photo.setImageBitmap(photo);
//			} else {
//
//			}
			break;
		case 3002://裁剪后获取结果
			if(resultCode == Activity.RESULT_OK){
				if(resultCode == RESULT_OK){
					Bitmap bitmap = BitmapUtils.decodeBitmap(headerFile.getAbsolutePath(),
							CropUtils.HEADER_WIDTH,
							CropUtils.HEADER_HEIGTH);
					my_photo.setImageBitmap(bitmap);
				}else{
					if(headerFile != null)headerFile.deleteOnExit();
					headerFile = null;
				}
			}
			
			break;
		case WHAT_PERSON_XINGQU:
			if (data != null) {
				mXingQuList.clear();
				mXingQuList.addAll((Collection<? extends TagEntity>) data
						.getParcelableArrayListExtra("attention"));
			}
			changeAdapter(true);
			break;
		case WHAT_PERSON_BODY:
			if (data != null) {
				mBodyList.clear();
				mBodyList.addAll((Collection<? extends TagEntity>) data
						.getParcelableArrayListExtra("attention"));

			}
			changeAdapter(true);
			break;
		}
	}

	/**
	 * 图片裁剪
	 * @param path
	 */
	private void onHandlerCropImage(String path){
		if(!SystemUtils.getScdExit()){
			ToastUtil.showSDCardBusy();
			return;
		}
		try{
			headerFile = StorageUtils.createHeaderFile();
			Uri outUri = Uri.fromFile(new File(path));
			Uri saveUri = Uri.fromFile(headerFile);
			Intent intent = CropUtils.createHeaderCropIntent(this,outUri,saveUri,true);
			startActivityForResult(intent,3002);
		}catch(Exception e){
			ToastUtil.showCreateFail();
		}
	}
	
	/**
	 * 根据uri查询相册所对应的图片地址
	 * @param uri
	 * @return
	 */
	private String getImageUrlByAlbum(Uri uri) {
		String[] imageItems = { MediaStore.Images.Media.DATA };
		Cursor cursor = managedQuery(uri, imageItems, null, null, null);
		int index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
		cursor.moveToFirst();
		String path = cursor.getString(index);
		return path;
	}
	
	/**
	 * 显示头像图片
	 * 
	 * @param str
	 */
	public void setPerspnImage() {
		headImagePath = mCus.getNormalHeadIcon();
		mImageLoader.displayImage(mCus.getSex(),headImagePath, my_photo);
	}

	/*
	 * 处理back事件
	 */
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			SystemUtils.hideSoftBord(getApplicationContext(), necheng);
			if (!isEdit() && isEdit) {
				onSaveYesOn();
				return true;
			}
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	public void onRefresh(PullToRefreshBase<ScrollView> refreshView) {
		HttpRestClient.doHttpFindCustomerInfoByCustId(null, null,
				SmartFoxClient.getLoginUserId(),
				SmartFoxClient.getLoginUserId(),
				new ObjectHttpResponseHandler(this) {
					@Override
					public Object onParseResponse(String content) {
						try {
							JSONObject jsonObject = new JSONObject(content);
							SmartFoxClient.getLoginUserInfo().setRoldid(jsonObject.getInt("roleId"));
						} catch (Exception e) {
						}
						return null;
					}

					@Override
					public void onSuccess(int statusCode, Object response) {
						super.onSuccess(statusCode, response);
						mCus = SmartFoxClient.getSmartFoxClient().getCustomerInfoEntity();
						initText();
					}

					@Override
					public void onFinish() {
						super.onFinish();
						mPullRefreshScrollView.onRefreshComplete();
					}
				});

	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		switch (parent.getId()) {
		case R.id.body_grid:
			if (position == mBodyList.size() - 1) {
				if (!isEdit) {
					toSearch(2, mBodyList.get(position));
				} else {
					onItem = true;
					mBodyList.remove(new TagEntity("000", "+"));
					Intent intent = new Intent();
					intent.setClass(PersonalInformationActivity.this,
							ChooseTagsActivity.class);
					intent.putExtra("type", 2);
					intent.putParcelableArrayListExtra("attentionInfo",
							(ArrayList<? extends Parcelable>) mBodyList);
					startActivityForResult(intent, WHAT_PERSON_BODY);
				}

			} else {
				if (!isEdit) {
					toSearch(2, mBodyList.get(position));
				}
			}
			break;
		case R.id.xingqu_grid:
			if (position == mXingQuList.size() - 1) {
				if (!isEdit) {
					toSearch(0, mXingQuList.get(position));
				} else {
					onItem = true;
					mXingQuList.remove(new TagEntity("000", "+"));
					Intent intent = new Intent();
					intent.setClass(PersonalInformationActivity.this,
							ChooseTagsActivity.class);
					intent.putParcelableArrayListExtra("attentionInfo",
							(ArrayList<? extends Parcelable>) mXingQuList);
					startActivityForResult(intent, WHAT_PERSON_XINGQU);
					overridePendingTransition(R.anim.anim_enter,
							R.anim.anim_exit);
				}
			} else {
				if (!isEdit) {
					toSearch(0, mXingQuList.get(position));
				}
			}
			break;
		}

	}

	private void toSearch(int type, TagEntity mTagEntity) {
		CustomerInfoEntity entity = new CustomerInfoEntity();
		entity.setId(SmartFoxClient.getLoginUserId());
		entity.setType(type);
		if (type == 2) {
			entity.setSameExperienceCode(Integer.valueOf(mTagEntity.getId()));
			entity.setSameExperience(mTagEntity.getName());
		} else {
			entity.setInterestName(mTagEntity.getName());
			entity.setInterestCode(mTagEntity.getId());
		}
		Intent intent = new Intent(getApplicationContext(),
				SearchByTagActivity.class);
		intent.putExtra("entity", entity);
		startActivity(intent);
	}
}
